package com.kma.ncpractice2013.auth;


import com.kma.ncpractice2013.dao.UserDAO;
import com.kma.ncpractice2013.facade.MailFacade;
import com.kma.ncpractice2013.facade.MailFacadeImpl;
import com.kma.ncpractice2013.model.User;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.SecureRandom;
import java.sql.*;
import java.util.UUID;


/**
 * User: Viktor
 * Date: 10/9/13
 */

public class RegistrationServlet extends HttpServlet {
    public static final int VALIDATION_OK = 0;
    public static final int USERNAME_NOT_UNIQUE = 1;
    //public static final int SQL_EXCEPTION = 2;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=UTF-8");
        String login = request.getParameter("r_login").toLowerCase();
        String pass = request.getParameter("r_password").toLowerCase();
        String username = request.getParameter("r_username");
	    String surname = request.getParameter("r_surname");
        String phone = request.getParameter("r_phone");
		if (!login.matches(".*[@].+"))
		{
			response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/register.jsp?errcode=2"));
			return;
		}
	    if (pass.length()<8)
	    {
		    response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/register.jsp?errcode=3"));
		    return;
	    }
	    if (username.length()<4)
	    {
		    response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/register.jsp?errcode=4"));
		    return;
	    }
	    if (surname.length()<4)
	    {
		    response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/register.jsp?errcode=4"));
		    return;
	    }
	    if (!phone.equals("") )
	    {
		    if (!phone.matches("[0-9]{3,14}$"))
		    {
		    response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/register.jsp?errcode=5"));
		    return;
		    }
	    }

	    try
        {


            if (validateInfo(login)==VALIDATION_OK)
            {
                SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
                secureRandom.setSeed(System.currentTimeMillis());
                byte[] salt = new byte[32];
                String token = UUID.randomUUID().toString();
                secureRandom.nextBytes(salt);
                String stringSalt = DatatypeConverter.printHexBinary(salt);

                MailFacade mail=new MailFacadeImpl();
	            String subject = "Reservation System registration confirmation";
                String letter = "Click on the following link to confirm your registration.\n" +
		                        MailFacadeImpl.home + "confirmation.jsp?token=" + token;
                try
                {
                    mail.sendLetter(login, subject, letter);

                }
                catch (Exception e)
                {
                    out.print(e.getMessage());
                    return;
                }
                Date d = new Date(System.currentTimeMillis());
                User user = new User();
                user.setAccessLevelId(User.AccessLevel.nonConfirmedCustomer);
                user.setLogin(login);
                user.setPhone(phone);
                user.setName(username);
	            user.setSurname(surname);
                user.setSalt(stringSalt);
                user.setRegistrationDate(d);
                user.setPassword(Crypto.getHash(stringSalt, pass, "SHA-256"));
                user.setRegistrationToken(token);
                user.setGroupId(User.Group.ordinaryCustomer);



                UserDAO dao = new UserDAO();

	            User oldUser = dao.getByLogin(login);
	            if (oldUser != null) dao.deleteById(oldUser.getId());

                dao.create(user);
                out.print("Confirmation letter has been sent to "+login);
                out.println("<a href=\"login.jsp\">login</a>");
                //response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/login.jsp"));

            }
            else
            {

            response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/register.jsp?errcode=1"));
            }
        }
        catch(Exception e)
        {
            out.println(e.getMessage());
        }



    }
	private int validateInfo(String login)
	{

        UserDAO dao = new UserDAO();
        User user = dao.getByLogin(login);

		return (user == null || user.getGroupId() == User.Group.nonRegisteredCustomer || user.getAccessLevelId() == User.AccessLevel.nonConfirmedCustomer) ? VALIDATION_OK : USERNAME_NOT_UNIQUE;

        //TODO: input validation

	}

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}


}
